package com.byzk.p2p.admin.base.util;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import java.io.File;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.io.IOException;
import java.awt.image.BufferedImage;


public final class QRcode{

  private static final int BLACK = 0xFF000000;
  private static final int WHITE = 0xFFFFFFFF;

	private final static String FORMAT = "/yyyy/MM/dd/";
	private final static String FOLDER = "/static/upload";

	/**
	 * 生成目录
	 * @return
	 */
	public static String generateFolder(){
		return FOLDER + new SimpleDateFormat(FORMAT).format(new Date());
	}
	
	
	/**
	 * 生成 UUID 文件名称
	 * @param fileName
	 * @return
	 */
	public static String generateFileName(String fileName){
		String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
		return (UUID.randomUUID() + suffix).replace("-", "");
	}
	
  private QRcode() {}

  
  public static BufferedImage toBufferedImage(BitMatrix matrix) {
    int width = matrix.getWidth();
    int height = matrix.getHeight();
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    for (int x = 0; x < width; x++) {
      for (int y = 0; y < height; y++) {
        image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
      }
    }
    return image;
  }

  
  public static void writeToFile(BitMatrix matrix, String format, File file)
      throws IOException {
    BufferedImage image = toBufferedImage(matrix);
    if (!ImageIO.write(image, format, file)) {
      throw new IOException("Could not write an image of format " + format + " to " + file);
    }
  }

  
  public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)
      throws IOException {
    BufferedImage image = toBufferedImage(matrix);
    if (!ImageIO.write(image, format, stream)) {
      throw new IOException("Could not write an image of format " + format);
    }
  }
  
  @SuppressWarnings({ "rawtypes", "unchecked" })
  public static String generateCode(HttpServletRequest request,String url) throws Exception{
	  String path = "";
	  try {
	    
		MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
	     
	    Map hints = new HashMap();
	    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
	    BitMatrix bitMatrix;
		
		bitMatrix = multiFormatWriter.encode(url, BarcodeFormat.QR_CODE, 400, 400,hints);

	    // 文件前缀
        String prefix = generateFolder();
        // 生成文件的绝对路径
        String sysPath = System.getProperty("static.file.path");
        
        if(StringUtils.isEmpty(sysPath)){
            path = request.getSession().getServletContext().getRealPath(prefix);
        }else{
            path += sysPath + "/" + prefix;
        }
        // 创建图片文件
        File targetFile = new File(path, "QRcode.jpg");
        if (!targetFile.exists()) {
        	targetFile.mkdirs();
        }else{
        	targetFile.delete();
        	targetFile.mkdirs();
        }
	        
	    MatrixToImageWriter.writeToFile(bitMatrix, "jpg", targetFile);
	    
		} catch (WriterException e) {
			e.printStackTrace();
		}
	  
	return path+"/QRcode.jpg";
  }
  
  public static void main(String[] args) {
	  String url="/alidata/server/apache-tomcat-8.0.29/webapps/p2p_platform/static/upload/2016/01/15/QRcode.jpg";
	  System.out.println(url.substring(url.indexOf("/static/"), url.length()));
  }

}